/**
 * Jenkins服务类
 * 提供Jenkins构建触发功能
 */

class JenkinsService {
  constructor(config = {}) {
    // 默认配置
    this.baseUrl = config.baseUrl || '/jenkins';
    this.username = config.username || 'hejianyi';
    this.apiToken = config.apiToken || '0b6e0d07-9dd1-4b33-8606-41f2227b87ab';
    this.buildToken = config.buildToken || 'vue-trigger-2025';
    this.jobName = config.jobName || 'contract-tenant-service-vue';
    
    // 调试模式
    this.debug = config.debug || false;
  }

  /**
   * 触发Jenkins构建
   * @param {string} jobName - Jenkins任务名称
   * @returns {Promise<boolean>} 构建是否成功触发
   */
  async triggerBuild(jobName = this.jobName) {
    try {
      const buildUrl = `${this.baseUrl}/job/${jobName}/build?token=${this.buildToken}&delay=0sec`;
      
      if (this.debug) {
        console.log('🚀 触发Jenkins构建:', buildUrl);
        console.log('👤 用户:', this.username);
      }

      const response = await fetch(buildUrl, {
        method: 'POST',
        headers: {
          'Authorization': `Basic ${btoa(`${this.username}:${this.apiToken}`)}`,
          'Content-Type': 'application/x-www-form-urlencoded',
          'Jenkins-Crumb': 'ignore'
        },
        credentials: 'include'
      });

      if (this.debug) {
        console.log('📊 响应状态:', response.status, response.statusText);
      }

      if (response.ok || response.status === 201 || response.status === 302) {
        console.log('✅ Jenkins构建已成功触发!');
        return true;
      } else {
        const errorText = await response.text();
        console.warn('⚠️ Jenkins构建触发失败:', response.status, errorText);
        
        // 尝试打开Jenkins页面
        this.openJenkinsPage(jobName);
        return false;
      }
    } catch (error) {
      console.error('❌ 触发Jenkins构建时出错:', error.message);
      
      // 网络错误时打开Jenkins页面
      this.openJenkinsPage(jobName);
      return false;
    }
  }

  /**
   * 打开Jenkins任务页面
   * @param {string} jobName - Jenkins任务名称
   */
  openJenkinsPage(jobName = this.jobName) {
    const jenkinsUrl = `http://172.20.20.28:8080/jenkins/job/${jobName}/`;
    
    if (typeof window !== 'undefined') {
      // 浏览器环境
      window.open(jenkinsUrl, '_blank');
    } else {
      // Node.js环境
      console.log('🔗 请手动访问:', jenkinsUrl);
    }
  }

  /**
   * 检查Jenkins任务状态
   * @param {string} jobName - Jenkins任务名称
   * @returns {Promise<Object>} 任务状态信息
   */
  async checkJobStatus(jobName = this.jobName) {
    try {
      const apiUrl = `${this.baseUrl}/job/${jobName}/api/json`;
      
      const response = await fetch(apiUrl, {
        method: 'GET',
        headers: {
          'Authorization': `Basic ${btoa(`${this.username}:${this.apiToken}`)}`,
          'Content-Type': 'application/json'
        },
        credentials: 'include'
      });

      if (response.ok) {
        return await response.json();
      } else {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }
    } catch (error) {
      console.error('❌ 检查任务状态时出错:', error.message);
      return null;
    }
  }

  /**
   * 获取最新构建信息
   * @param {string} jobName - Jenkins任务名称
   * @returns {Promise<Object>} 最新构建信息
   */
  async getLastBuildInfo(jobName = this.jobName) {
    try {
      const jobStatus = await this.checkJobStatus(jobName);
      if (jobStatus && jobStatus.lastBuild) {
        const buildUrl = jobStatus.lastBuild.url.replace('http://172.20.20.28:8080', this.baseUrl);
        
        const response = await fetch(`${buildUrl}/api/json`, {
          method: 'GET',
          headers: {
            'Authorization': `Basic ${btoa(`${this.username}:${this.apiToken}`)}`,
            'Content-Type': 'application/json'
          },
          credentials: 'include'
        });

        if (response.ok) {
          return await response.json();
        }
      }
      return null;
    } catch (error) {
      console.error('❌ 获取构建信息时出错:', error.message);
      return null;
    }
  }

  /**
   * 更新配置
   * @param {Object} newConfig - 新的配置对象
   */
  updateConfig(newConfig) {
    Object.assign(this, newConfig);
    if (this.debug) {
      console.log('🔧 配置已更新:', newConfig);
    }
  }

  /**
   * 获取当前配置
   * @returns {Object} 当前配置
   */
  getConfig() {
    return {
      baseUrl: this.baseUrl,
      username: this.username,
      apiToken: this.apiToken,
      buildToken: this.buildToken,
      jobName: this.jobName,
      debug: this.debug
    };
  }
}

// 使用Chrome MCP服务触发Jenkins构建
  JenkinsService.prototype.triggerBuildViaBrowser = async function(jobName = this.jobName) {
    try {
      const jenkinsUrl = `http://172.20.20.28:8080/jenkins/job/${jobName}/`;
      
      if (this.debug) {
        console.log('🚀 准备通过浏览器触发Jenkins构建:', jenkinsUrl);
      }
      
      // 使用Chrome MCP服务打开Jenkins页面
      await new Promise((resolve) => {
        if (typeof window !== 'undefined') {
          // 在浏览器环境中，使用MCP服务
          const event = new CustomEvent('triggerJenkinsViaBrowser', {
            detail: {
              url: jenkinsUrl,
              jobName: jobName
            }
          });
          window.dispatchEvent(event);
          resolve(true);
        } else {
          // 在Node.js环境中，打印提示信息
          console.log('🔗 请在浏览器环境中使用此功能，通过Chrome MCP服务触发构建');
          resolve(false);
        }
      });
      
      console.log('✅ 已触发浏览器打开Jenkins页面并尝试点击Build Now按钮');
      return true;
    } catch (error) {
      console.error('❌ 通过浏览器触发Jenkins构建时出错:', error.message);
      return false;
    }
  };

  // 默认实例
  export const jenkinsService = new JenkinsService();

// 类导出
export default JenkinsService;